import axios from 'axios'
import router from '../router'

// if(process.env.NODE_ENV == 'development') {
//   const baseURL = '/api'
// } else {
//   const baseURL = '/'
// }

const baseURL = (process.env.NODE_ENV == 'development') ? '/api' : '/v1'

const instance = axios.create({
  baseURL
})

// 请求拦截
instance.interceptors.request.use(config => {
  const token = localStorage.getItem('token')

  token && (config.headers['Authorization'] = 'Bearer ' + token)

  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截
instance.interceptors.response.use(response => {
  if(response.data.token) {
    localStorage.setItem('token', response.data.token)
  }

  return response
}, error => {
  const _response = error.response

  switch(_response.status) {
    case 401:
      localStorage.removeItem('token')

      router.replace({
        path: '/login',
        query: {
          redirect: router.currentRoute.fullPath
        }
      })
      break
  }

  return Promise.reject(error)
})

export default instance